import axios from 'axios'
import Vue from 'vue'
import { Message } from 'element-ui'
import router from '../router'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url 
  // baseURL: window.ipConfigUrl.baseURL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (token) {
      config.headers['Authorization'] = token
    }

    // IE10 get请求因为缓存问题，导致无法发起真实请求
    if (config.method === 'get') {
      if (!config.params) {
        config.params = {}
      }
      // config.params['_t'] = new Date().getTime()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    return response
  },
  error => {
    let message = null
    if (error.response) {
      if (error.response.status === 401) {
        message = "非法的身份或者身份过期，需要重新登录"
        store.dispatch('Logout').then(res => {
          router.push('/login')
        })
      } else if (error.response.status === 403) {
        // console.error('未授权访问，给用户提示或路由到一个其他错误页面')
        router.push('/403')
      } else {
        const data = error.response.data
        console.log(data);
        if (data && data.status === 500 && data.message) {
          message = data.message
        }
      }
    }
    Message({
      message: message || '服务器繁忙',
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
